package com.qianguo.shop.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;

import com.eva.androidlibrary.utils.ScanCamera;
import com.qianguo.shop.R;
import com.qianguo.shop.base.BaseNoTitleActivity;
import com.zh.idcard.ocr.ZHOcr;
import com.zh.idcard.vo.CardInfo;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.ViewById;

import java.io.File;
import java.io.FileOutputStream;

/**
 * 身份证识别页面
 *
 * @author GUXIA318
 * @date 2015-10-26 15:53
 */
@Fullscreen
@EActivity(R.layout.activity_scan_id_card)
public class ScanIDCardActivity extends BaseNoTitleActivity implements SurfaceHolder.Callback, SensorEventListener, ScanCamera.AutoFocusSuccessListener {

    private static final int BITMAP_CACHED_OK = 1;
    private static final int BITMAP_CACHED_FAILED = 0;

    /**图像*/
    @ViewById(R.id.capture_preview)
    SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private ScanCamera mOcrCamera;
    /**身份证正面识别图像回调结果*/
    private byte[] A_data = null;
    /**识别正面*/
    private final int A_TYPE = 100;

    private Bitmap mBitmap;
    private CardInfo mCardInfo;
    private File mFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    public static void jumpToScanIDCard(Context context) {
        Intent intent = new Intent(context, ScanIDCardActivity_.class);
        context.startActivity(intent);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == A_TYPE) {
                A_data = msg.getData().getByteArray("img_data");
                if (A_data != null && A_data.length > 0) {
                    // TODO: 2015-10-28 识别身份证成功
                    mBitmap = bytes2Bitmap(A_data);
                    getScanResult();
                    new SaveImageToGalleryTask().execute();
                } else {
                    showSnackBar(ScanIDCardActivity.this, "没有识别到相关信息，请重新拍摄。");
                }
            } else {
                showSnackBar(ScanIDCardActivity.this, "拍摄失败");
            }
            mOcrCamera.startDisplay();
        }
    };

    @Override
    protected void initializeUI() {
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.addCallback(this);
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mOcrCamera = new ScanCamera(this, mHandler, this);

        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccel = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    }

    @Click(R.id.btn_ok)
    void clickOk() {
        mOcrCamera.autoFocusAndTakePic(A_TYPE);
    }

    @Click(R.id.btn_cancel)
    void clickCancel() {
        finish();
    }

    @Click(R.id.capture_preview)
    void clickFocus() {
        mOcrCamera.autoFocus();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            mOcrCamera.openCamera(holder);
            if (mOcrCamera.isSupportFlash(Camera.Parameters.FLASH_MODE_AUTO)) {
                mOcrCamera.setCameraFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
            }else if(mOcrCamera.isSupportFlash(Camera.Parameters.FLASH_MODE_OFF)){
                mOcrCamera.setCameraFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            }
        } catch (Exception e) {
            Toast.makeText(ScanIDCardActivity.this, "相机未正常启动!", Toast.LENGTH_SHORT);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (width > height) {
            mOcrCamera.setPreviewSize(width, height);
        } else {
            mOcrCamera.setPreviewSize(height, width);
        }
        mOcrCamera.startDisplay();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mOcrCamera.closeCamera();
    }

    @Override
    protected void onResume() {
        A_data = null;
        mSensorManager.registerListener(this, mAccel, SensorManager.SENSOR_DELAY_UI);
        super.onResume();
    }

    /**通过加速度传感器实现自动对焦*/
    private SensorManager mSensorManager;
    private Sensor mAccel;
    private boolean mInitialized = false;
    private float mLastX = 0;
    private float mLastY = 0;
    private float mLastZ = 0;
    private boolean mInvalidate = false;
    private boolean mAutoFocus = true;
    /**通过加速度传感器实现自动对焦*/
    @Override
    public void onSensorChanged(SensorEvent event) {
        if (!(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)) {
            return;
        }

        if (mInvalidate == true) {
            mInvalidate = false;
        }

        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];
        if (!mInitialized){
            mLastX = x;
            mLastY = y;
            mLastZ = z;
            mInitialized = true;
        }
        float deltaX  = Math.abs(mLastX - x);
        float deltaY = Math.abs(mLastY - y);
        float deltaZ = Math.abs(mLastZ - z);

        if (deltaX > .5 && mAutoFocus){
            mAutoFocus = false;
            mOcrCamera.autoFocus();
        }
        if (deltaY > .5 && mAutoFocus){
            mAutoFocus = false;
            mOcrCamera.autoFocus();
        }
        if (deltaZ > .5 && mAutoFocus){
            mAutoFocus = false;
            mOcrCamera.autoFocus();
        }
        mLastX = x;
        mLastY = y;
        mLastZ = z;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    @Override
    public void onAutoFocusSuccess() {
        mAutoFocus = true;
    }

    /**
     * byte转换为bitmap
     * */
    public Bitmap bytes2Bitmap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

    /**
     * 获得扫描结果
     * */
    @Background
    void getScanResult(){
        showLoadingDialog(ScanIDCardActivity.this);
        ZHOcr ocr = new ZHOcr();
        mCardInfo = ocr.getIdCardInfo(this, A_data, null);
        closeLoadingDialog();
        if (mCardInfo == null || TextUtils.isEmpty(mCardInfo.getName())){
            showWarningDialog(ScanIDCardActivity.this, "提示", "没有识别到身份证信息，请重试。", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    closeDialog();
                }
            });
        }
    }

    /**
     * 保存bitmap到文件
     * */
    class SaveImageToGalleryTask extends AsyncTask<String, String, Integer> {
        @Override
        protected Integer doInBackground(String... params) {
            showLoadingDialog(ScanIDCardActivity.this);
            if (mBitmap == null) {
                return 0;
            }

            mFile = new File(getCacheDir(), "cropped");
            if (mFile.exists()) {
                mFile.delete();
            }

            try {
                mFile.createNewFile();
                FileOutputStream fileOutputStream = new FileOutputStream(mFile);
                mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
                // 其次把文件插入到系统图库
                MediaStore.Images.Media.insertImage(getContentResolver(), mFile.getAbsolutePath(), "cropped", null);
                // 最后通知图库更新
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file:///" + mFile.getAbsolutePath()));
                sendBroadcast(intent);
                return BITMAP_CACHED_OK;
            } catch (Exception e) {
                e.printStackTrace();
                return BITMAP_CACHED_FAILED;
            }
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            closeLoadingDialog();
            switch (integer) {
                case BITMAP_CACHED_FAILED:
                    //bitmap为空或者文件操作异常终止导致未能保存成功
                    showSnackBar(ScanIDCardActivity.this,"图片保存未成功，请手动选择图片。");
                    break;
                case BITMAP_CACHED_OK:
                    Intent intent = new Intent(ScanIDCardActivity.this, RealNameAuthActivity_.class);
                    intent.putExtra("picPath", mFile.getAbsolutePath());
                    intent.putExtra("realName", mCardInfo.getName());
                    intent.putExtra("idNum", mCardInfo.getNum());
                    startActivity(intent);
                    break;
            }
        }
    }

}
